import feedparser # https://feedparser.readthedocs.io/en/latest/
from download import Video, get_info_yt_video


class CheckFeed:
    def __init__(self, yt_channel_id: str, items_quantity: int = 5):
        self.items_quantity = self.__check_quantity(items_quantity)
        self.feed_url = f"https://www.youtube.com/feeds/videos.xml?channel_id={yt_channel_id}"
        self.title = None
        self.videos = self.read()
        self.upadates = []

    def __check_quantity(self, quantity: int):
        if not isinstance(quantity, int) or quantity <= 0:
            raise ValueError("Error. You have to provide an integer value more then zero")
        else:
            return quantity

    def read(self, items_quantity: int = 0) -> list[Video]:
        self.videos = []
        items_quantity = self.__check_quantity(items_quantity) if items_quantity != 0 \
                                                               else self.items_quantity
        feed = feedparser.parse(self.feed_url)
        try:
            self.title = feed['channel']['title']
        except KeyError:
            raise ValueError('Suppose invalid youtube channel ID. \
Check config.py file')

        for entry in feed.entries:
            # limitation video items
            if len(self.videos) == items_quantity: break 
            try:
                # TODO make optional live chacking
                video = get_info_yt_video(entry['link'])
            except Exception as err:
                if 'This live event will begin in a few moments' in str(err):
                    pass
            else:
                self.videos.append(video)
        return self.videos

